<template>
  <div class="sensor-history-container">
    <h1>传感器历史数据</h1>
    
    <!-- 传感器类型选择器 -->
    <div class="sensor-selector">
      <button 
        v-for="sensor in sensors" 
        :key="sensor.type"
        :class="['sensor-btn', { active: selectedSensor === sensor.type }]"
        @click="selectSensor(sensor.type)"
      >
        {{ sensor.name }}
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <table class="history-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>设备ID</th>
            <th>传感器名称</th>
            <th>数值</th>
            <th>单位</th>
            <th>记录时间</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in sensorData" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ item.deviceId }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.value }}</td>
            <td>{{ getUnit(selectedSensor) }}</td>
            <td>{{ formatDate(item.createdAt) }}</td>
          </tr>
          <tr v-if="sensorData.length === 0">
            <td colspan="6" class="no-data">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控制 -->
    <div class="pagination">
      <button @click="previousPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useStore } from '@/store/index.js';

const sensors = ref([
  { type: 'Air_temp', name: '空气温度', unit: '℃' },
  { type: 'Air_water', name: '空气湿度', unit: '%' },
  { type: 'SoilTemperature', name: '土壤温度', unit: '℃' },
  { type: 'SoilWater', name: '土壤湿度', unit: '%' },
  { type: 'Soil_N', name: '土壤氮含量', unit: 'mg/kg' },
  { type: 'Soil_L', name: '土壤磷含量', unit: 'mg/kg' },
  { type: 'Soil_K', name: '土壤钾含量', unit: 'mg/kg' },
]);

const selectedSensor = ref('Air_temp');
const allSensorData = ref([]);
const currentPage = ref(1);
const pageSize = 20;

const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

const getUnit = (sensorType) => {
  const sensor = sensors.value.find(s => s.type === sensorType);
  return sensor ? sensor.unit : '';
};

const getApiPath = (sensorType) => {
  const pathMap = {
    'Air_temp': '/api/soil/air_temp',
    'Air_water': '/api/soil/air_water',
    'SoilTemperature': '/api/soil/temperature',
    'SoilWater': '/api/soil/water',
    'Soil_N': '/api/soil/N',
    'Soil_L': '/api/soil/L',
    'Soil_K': '/api/soil/K',
  };
  return pathMap[sensorType] || '/api/soil';
};

const fetchSensorData = async (sensorType) => {
  try {
    const userStore = useStore();
    const token = userStore.token;
    const apiPath = getApiPath(sensorType);
    
    const response = await axios.get(`${apiPath}/all?sensorType=${sensorType}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    
    allSensorData.value = response.data || [];
    currentPage.value = 1; // 重置到第一页
  } catch (error) {
    console.error('获取传感器数据失败:', error);
    allSensorData.value = [];
  }
};

const selectSensor = (sensorType) => {
  selectedSensor.value = sensorType;
  fetchSensorData(sensorType);
};

// 计算当前页显示的数据
const sensorData = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return allSensorData.value.slice(start, end);
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(allSensorData.value.length / pageSize);
});

const previousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

onMounted(() => {
  fetchSensorData(selectedSensor.value);
});
</script>

<style scoped>
.sensor-history-container {
  width: 95%;
  height: 670px;
  padding: 20px;
  font-family: 'Roboto', sans-serif;
  background-color: #1e2a38;
  color: #f1f1f1;
  border-radius: 12px;
  margin: 0 auto;
  box-shadow: 0 0 20px 5px rgb(22, 92, 194);
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 22px;
  color: #417fd9;
  font-weight: bold;
  text-transform: uppercase;
}

/* 传感器选择器样式 */
.sensor-selector {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #0f1b2b;
  border-radius: 8px;
}

.sensor-btn {
  padding: 8px 16px;
  background-color: #263344;
  color: #7aa3e0;
  border: 1px solid #3480ee;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.sensor-btn:hover {
  background-color: #3480ee;
  color: #fff;
  transform: translateY(-2px);
}

.sensor-btn.active {
  background-color: #2990ff;
  color: #fff;
  border-color: #2990ff;
}

/* 表格容器 */
.table-wrapper {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

/* 隐藏滚动条 */
.table-wrapper::-webkit-scrollbar {
  width: 6px;
}

.table-wrapper::-webkit-scrollbar-track {
  background: #0f1b2b;
  border-radius: 3px;
}

.table-wrapper::-webkit-scrollbar-thumb {
  background: #3480ee;
  border-radius: 3px;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
  background: #2990ff;
}

.history-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.history-table th,
.history-table td {
  padding: 12px 15px;
  border: 1px solid #333;
  text-align: center;
}

.history-table th {
  background-color: #0f1b2b;
  color: #7aa3e0;
  border-bottom: 2px solid #3480ee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.history-table td {
  background-color: #263344;
  color: #f1f1f1;
}

.history-table tr:nth-child(even) td {
  background-color: #1f2b3d;
}

.history-table tr:hover td {
  background-color: #4b8ff3;
  color: #fff;
  cursor: pointer;
}

.no-data {
  padding: 40px !important;
  color: #7aa3e0;
  font-size: 16px;
}

/* 分页控制 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 15px;
  background-color: #0f1b2b;
  border-radius: 8px;
}

.pagination button {
  padding: 8px 20px;
  background-color: #2990ff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.pagination button:hover:not(:disabled) {
  background-color: #3480ee;
  transform: scale(1.05);
}

.pagination button:disabled {
  background-color: #263344;
  color: #666;
  cursor: not-allowed;
}

.pagination span {
  color: #7aa3e0;
  font-size: 14px;
}
</style>

